<?php

namespace App\Observers;

use App\Models\Reply;
use App\Notifications\TopicReplied;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ReplyObserver
{
    //存入之前
    public function saving(Reply $reply){
        $reply->content = clean($reply->content,'my_editor_reply')?:'[敏感内容，已被系统过滤]';
    }

    public function saved(Reply $reply){
        $reply->topic->reply_count = $reply->topic->replies->count();
        $reply->topic->last_reply_user_id = $reply->user_id;
        $reply->topic->save() ;
        //触发通知
        $reply->topic->user->topicNotify(new TopicReplied($reply));
    }


    public function deleted(Reply $reply){
        $reply->topic->reply_count = $reply->topic->replies->count();
        //todo:查replies表不合适，因为速度会变慢
        $last_reply_user_id = DB::table('replies')
            ->where('topic_id',$reply->topic->id)
            ->latest()->value('user_id');
        $reply->topic->last_reply_user_id = $last_reply_user_id??0;
        $reply->topic->save() ;
    }
}
